import Api from '@/serverApi'
import { get } from '@/utils/request'
import * as types from './types'

const state = {
  hotKnowledge: [],
  openCourse: {}
}

const mutations = {
  [types.GET_HOT_KNOWLEDGE] (state) {
    console.log(types.GET_HOT_KNOWLEDGE)
  },
  [types.GET_HOT_KNOWLEDGE_SUCCESS] (state, data) {
    state.hotKnowledge = data
    console.log(types.GET_HOT_KNOWLEDGE_SUCCESS)
  },
  [types.GET_HOT_KNOWLEDGE_FAILED] (state, data) {
    console.log(types.GET_HOT_KNOWLEDGE_FAILED)
  },
  [types.GET_OPEN_COURSE_SUCCESS] (state, data) {
    state.openCourse = data
  }
}

const actions = {
  async [types.getHotKnowledge] ({ commit, state }) {
    commit(types.GET_HOT_KNOWLEDGE)
    try {
      const data = await get(Api.HOT_KNOWLEDGE)
      commit(types.GET_HOT_KNOWLEDGE_SUCCESS, data)
    } catch (err) {
      commit(types.GET_HOT_KNOWLEDGE_FAILED)
    }
  },
  async [types.getOpenCourse] ({ commit, state }) {
    try {
      const data = await get(Api.OPEN_COURSE)
      commit(types.GET_OPEN_COURSE_SUCCESS, data)
    } catch (err) {
      commit(types.GET_OPEN_COURSE_FAILED)
    }
  },
  [types.getHomeInfo] ({ dispatch }) {
    [types.getOpenCourse, types.getHotKnowledge].forEach(dispatch)
  }
}

export default {
  state,
  mutations,
  actions
}
